package top.yaofengqiao.springcloudsimple.web.starter.security.filter;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;
import top.yaofengqiao.springcloudsimple.auth.api.dto.TokenAuthResultDTO;
import top.yaofengqiao.springcloudsimple.common.constant.AuthConstant;
import top.yaofengqiao.springcloudsimple.common.constant.ResponseCode;
import top.yaofengqiao.springcloudsimple.common.util.AppException;
import top.yaofengqiao.springcloudsimple.web.starter.security.TokenCache;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author yfq
 * @date 2024/4/11 11:42
 * @description 每次请求检查请求头是否携带Authorization
 * 如果携带了，就将当前用户信息设置到当前线程
 */
@Slf4j
public class TokenFilter extends OncePerRequestFilter {
    @Resource
    private TokenCache tokenCache;

    @Override
    @SuppressWarnings("all")
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String token = request.getHeader(AuthConstant.AUTHORIZATION);

        if (StrUtil.isNotEmpty(token)) {
            // 存储用户信息
            TokenAuthResultDTO tokenAuthResultDTO = tokenCache.getToken(token);
            if (tokenAuthResultDTO == null || !tokenAuthResultDTO.pass())
                throw new AppException(ResponseCode.NO_AUTHENTICATION);

            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(tokenAuthResultDTO, null, null);

            // 存储用户信息到当前线程
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }

        filterChain.doFilter(request, response);
    }

}
